package com.hqyj.web;

import com.hqyj.util.TokenUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.http.server.reactive.ServerHttpRequest;

//@Component
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request =  exchange.getRequest();
        //如果这是一个登录请求，放行
        if(request.getURI().toString().contains("login")){
            return chain.filter(exchange);
        }
        //如果不是登录请求，那么查看请求中是否包含了token, 验证token的正确性。
        String tokenval = request.getHeaders().getFirst("token");
        //验证token是否正确
        boolean flag = TokenUtil.verify(tokenval);
        //如果token正确，放行
        if(flag){
            return chain.filter(exchange);
        }
        // token不正确，禁止访问，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2.结束处理
        return exchange.getResponse().setComplete();

    }
}
